import { TokenService } from '../services/tokenService.js';
import { validateRequest, createTokenSchema, updateTokenSchema } from '../utils/validation.js';
import { formatSuccessResponse } from '../utils/errors.js';
import { authenticate } from '../middleware/auth.js';

export default async function tokenRoutes(fastify, options) {
  const tokenService = new TokenService(fastify.prisma);
  
  /**
   * 获取所有令牌
   */
  fastify.get('/', {
    onRequest: [authenticate],
  }, async (request, reply) => {
    const { category, isFavorite, search, limit, offset, orderBy, orderDir } = request.query;
    
    const result = await tokenService.getUserTokens(request.user.userId, {
      category,
      isFavorite: isFavorite === 'true',
      search,
      limit: parseInt(limit) || 100,
      offset: parseInt(offset) || 0,
      orderBy: orderBy || 'createdAt',
      orderDir: orderDir || 'desc',
    });
    
    return formatSuccessResponse(result);
  });
  
  /**
   * 创建令牌
   */
  fastify.post('/', {
    onRequest: [authenticate],
  }, async (request, reply) => {
    const data = validateRequest(createTokenSchema, request.body);
    const { password } = request.body; // 用于加密
    
    if (!password) {
      throw new Error('需要提供密码以加密令牌');
    }
    
    const token = await tokenService.createToken(
      request.user.userId,
      data,
      password
    );
    
    return formatSuccessResponse(token, '令牌创建成功');
  });
  
  /**
   * 导入令牌（从URI）
   */
  fastify.post('/import', {
    onRequest: [authenticate],
  }, async (request, reply) => {
    const { uri, password } = request.body;
    
    if (!uri || !password) {
      throw new Error('需要提供URI和密码');
    }
    
    const token = await tokenService.importFromUri(
      request.user.userId,
      uri,
      password
    );
    
    return formatSuccessResponse(token, '令牌导入成功');
  });
  
  /**
   * 获取单个令牌
   */
  fastify.get('/:id', {
    onRequest: [authenticate],
  }, async (request, reply) => {
    const token = await tokenService.getToken(request.params.id, request.user.userId);
    return formatSuccessResponse(token);
  });
  
  /**
   * 更新令牌
   */
  fastify.put('/:id', {
    onRequest: [authenticate],
  }, async (request, reply) => {
    const data = validateRequest(updateTokenSchema, request.body);
    
    const token = await tokenService.updateToken(
      request.params.id,
      request.user.userId,
      data
    );
    
    return formatSuccessResponse(token, '令牌更新成功');
  });
  
  /**
   * 删除令牌
   */
  fastify.delete('/:id', {
    onRequest: [authenticate],
  }, async (request, reply) => {
    await tokenService.deleteToken(request.params.id, request.user.userId);
    return formatSuccessResponse(null, '令牌删除成功');
  });
  
  /**
   * 切换收藏状态
   */
  fastify.patch('/:id/favorite', {
    onRequest: [authenticate],
  }, async (request, reply) => {
    const isFavorite = await tokenService.toggleFavorite(
      request.params.id,
      request.user.userId
    );
    
    return formatSuccessResponse({ isFavorite });
  });
  
  /**
   * 生成TOTP验证码
   */
  fastify.post('/:id/generate', {
    onRequest: [authenticate],
  }, async (request, reply) => {
    const { password } = request.body;
    
    if (!password) {
      throw new Error('需要提供密码以解密令牌');
    }
    
    const result = await tokenService.generateCode(
      request.params.id,
      request.user.userId,
      password
    );
    
    return formatSuccessResponse(result);
  });
  
  /**
   * 验证TOTP验证码
   */
  fastify.post('/verify', {
    onRequest: [authenticate],
  }, async (request, reply) => {
    const { tokenId, code, password } = request.body;
    
    if (!tokenId || !code || !password) {
      throw new Error('需要提供令牌ID、验证码和密码');
    }
    
    const isValid = await tokenService.verifyCode(
      tokenId,
      request.user.userId,
      code,
      password
    );
    
    return formatSuccessResponse({ valid: isValid });
  });
  
  /**
   * 搜索令牌
   */
  fastify.get('/search', {
    onRequest: [authenticate],
  }, async (request, reply) => {
    const { q, category } = request.query;
    
    const result = await tokenService.getUserTokens(request.user.userId, {
      search: q,
      category,
    });
    
    return formatSuccessResponse(result);
  });
  
  /**
   * 获取收藏的令牌
   */
  fastify.get('/favorites', {
    onRequest: [authenticate],
  }, async (request, reply) => {
    const result = await tokenService.getUserTokens(request.user.userId, {
      isFavorite: true,
    });
    
    return formatSuccessResponse(result);
  });
  
  /**
   * 获取最近使用的令牌
   */
  fastify.get('/recent', {
    onRequest: [authenticate],
  }, async (request, reply) => {
    const result = await tokenService.getUserTokens(request.user.userId, {
      limit: 10,
      orderBy: 'lastUsed',
      orderDir: 'desc',
    });
    
    return formatSuccessResponse(result);
  });
  
  /**
   * 批量删除
   */
  fastify.post('/batch-delete', {
    onRequest: [authenticate],
  }, async (request, reply) => {
    const { tokenIds } = request.body;
    
    if (!tokenIds || !Array.isArray(tokenIds)) {
      throw new Error('需要提供令牌ID数组');
    }
    
    const count = await tokenService.batchDelete(tokenIds, request.user.userId);
    
    return formatSuccessResponse({ count }, `成功删除${count}个令牌`);
  });
  
  /**
   * 导出令牌
   */
  fastify.get('/export', {
    onRequest: [authenticate],
  }, async (request, reply) => {
    const tokens = await tokenService.exportTokens(request.user.userId);
    
    return formatSuccessResponse(tokens);
  });
}


